package org.dei.perla.utils;

import org.dei.perla.utils.pipe.Pipe;
import org.dei.perla.utils.waiter.Waitable;
import org.dei.perla.utils.waiter.Waiter;

class MultiplexedPipeThread<K> extends Waiter<Pipe<K>> implements Runnable {
	
	private Pipe<K> outPipe;
	
	public MultiplexedPipeThread(Pipe<K> inPipe, Pipe<K> outPipe) {
		super();
		this.addWaitable(inPipe.getWaitable());
		this.outPipe = outPipe;
	}

	public void run(){
		Waitable<Pipe<K>> waitable;
		while(true){
			waitable = this.waitNext();
			K myStuff =  waitable.getParentComponent().dequeue();
			if (myStuff != null) {
				outPipe.enqueue(myStuff);
			} else {
				this.removeWaitable(waitable);
				waitable.getParentComponent().stop();
				this.stop();
				break;
			}
		}
	}
}
